package cn.hyy.hrm.handler;

import cn.hyy.hrm.client.FileClient;
import cn.hyy.hrm.config.RabbitConfig;
import com.rabbitmq.client.Channel;
import feign.Response;
import org.apache.commons.io.IOUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Component
public class FileQueueHandler {

    @Autowired
    private FileClient fileClient;

    @Value("${project.home.path}")
    private String projectPath;

    @RabbitListener(queues = {RabbitConfig.QUEUE_COURSE_HOME})
    public void receive_email(String fileId, Message message, Channel channel) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        //从fastdfs中下载文件
        try {
            Response response = fileClient.download(fileId);
            Response.Body body = response.body();
            inputStream = body.asInputStream();

            //前端项目该文件的路径
            outputStream = new FileOutputStream(projectPath);

            IOUtils.copy(inputStream,outputStream);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (outputStream!=null)
                    outputStream.close();
                if(inputStream!=null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

}
